import axios from 'axios';
import { msg, notification } from 'antd';
import { routerRedux } from 'dva/router';
import md5 from 'js-md5';
import store from '../index';
const codeMessage = {
  200: '服务器成功返回请求的数据',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）',
  204: '删除数据成功。',
  207: '频繁操作',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）或登录已失效。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器',
  502: '网关错误',
  503: '服务不可用，服务器暂时过载或维护',
  504: '网关超时',
};

function checkStatus(response) {
  const { data, config } = response
  if (response.status >= 200 && response.status < 300) {
    if (data && data.httpCode === 200) {
      return data;
    } else {
      const { msg, httpCode } = data;
      const msgTips = msg || '系统错误'
      notification.error({
        message: `请求错误 ${httpCode}: ${response.config.url}`,
        description: msgTips,
      });

      //判断是否需要抛出错误
      // if(config.method==='get' && (httpCode===403 || httpCode === 401 || httpCode === 404)) {

      // }
      const error = new Error(msgTips);
      error.response = response;
      throw error;
    }
  } 
  // else {
  //   notification.error({
  //     message: `请求错误 ${response.status}: ${response.config.url}`,
  //     description: data || '系统错误',
  //   });
  // }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

//url: configs.url.replace('/api','/api/admin')
export default function request(configs = {}) {
  const { url, data:body, params = {}, method = 'get' } = configs;
  const timestamp = new Date().getTime();
  const p = {...body, ...params, timestamp, 'xm-name': 'SSM', 'dev-name': 'spf'}
  //创建签名
  const sign = createSign(p);

  return axios.request({ url, data:body, method, params: {...params, timestamp, sign}})
    .then(checkStatus).catch((e) => {

      const { dispatch } = store;
      if(e.response) {
        let {data, status, statusText, config} = e.response;
        if(status === 200) {
          status = data.httpCode;
          statusText = data.data;
        } else {
          statusText = data;
        }

        //网络连接超时
        if(status === 504) {
          dispatch(routerRedux.push('/exception/504'));
          return;
        }
        if(status === 400) {
          notification.error({
            message: `请求错误 ${status}: ${config.url}`,
            description: statusText || '系统错误',
          });
          return;
        }
        //未登录
        if (status === 401) {
          dispatch({ type: 'app/logout' });
          return;
        }
        //没有权限
        if (status === 403 && config.method === 'get') {
          dispatch(routerRedux.push('/exception/403'));
          return;
        }

        if (status >= 404 && status < 422 && config.method === 'get') {
          dispatch(routerRedux.push('/exception/404'));
          return;
        }
      } else {
        dispatch(routerRedux.push('/exception/504'));
      }
    });
}

function createSign(data) {
  let keyArr = Object.keys(data);
  keyArr.sort();
  let str = "";
  for (var i = 0; i < keyArr.length; i++){
    if (data[keyArr[i]] === null || data[keyArr[i]] === "" || data[keyArr[i]] === undefined) {
      continue;
    }
    str += keyArr[i] + "=" + data[keyArr[i]]+"&";
  }
  str = str.substring(0, str.length - 1);
  var signToken = localStorage.signToken;
  const sign = md5(signToken + str + signToken);
  return sign;
}

//请求前和请求结束的拦截器
// axios.interceptors.request.use(function (config) {
//   return config;
// }, function (error) {
//   return Promise.reject(error);
// });
//
// axios.interceptors.response.use(function (response) {
//   NProgress.done()//结束进度条
//   return response;
// }, function (error) {
//   return Promise.reject(error);
// });
